package com.ruoyi.quartz.task;

import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.my.domain.GrTuanInfo;
import com.ruoyi.my.service.IGrTuanInfoService;
import com.ruoyi.quartz.Constant;
import org.apache.commons.math3.random.RandomDataGenerator;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 定时任务调度测试
 */
@Component("xbTask")
public class XbTask {

    @Autowired
    private IGrTuanInfoService tuanInfoService;
    private static final Logger logger = LoggerFactory.getLogger(XbTask.class);
    boolean zk8Flag = true;//赚客吧 爬虫开关
    boolean z0818Flag = false;//0818 爬虫开关
    private static String yearNo = "2021-";//赚客吧-分割词

    public void packXianBao() {
        int count = 0;
        Threads.sleep(new RandomDataGenerator().nextInt(10, 30) * 1000);
        if (zk8Flag) {
            count = getZk8Count(count);
        }
        if (z0818Flag) {
            try {
                String post = HttpUtils.sendGetMuliParam(Constant.XB0818_HEAD + Constant.XB_TIMES, "",
                        "gbk", Constant.XB0818_HEAD);
                Document document = Jsoup.parse(post);
                Element postList = document.getElementById("redtag");
                if (postList != null) {
                    pack0818(postList, count);
                }
            } catch (Exception e) {
                logger.error("0818线报异常...");
            }
        }
//        if (logger.isErrorEnabled())
//            logger.error("更新数量：" + count);
    }

    public int getZk8Count(int count) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("Cookie", Constant.ZUANKE8_COOKIE);
            String hxzContent = HttpUtils.sendGetWithHead("http://www.zuanke8.com/forum-15-1.html",
                    "", map);
            Document hxzDome = Jsoup.parse(hxzContent);
            Element hxzEle = hxzDome.getElementById("alist");
            if (hxzEle != null) {
                Elements hxzEs = hxzEle.getElementsByTag("a");
                if (hxzEs != null && hxzEs.size() > 0) {
                    count = packZk(hxzEs, count);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ZK8线报异常" + e.getMessage());
        }
        return count;
    }

    private int packZk(Elements elements, int count) {
        Calendar cal = Calendar.getInstance();
        yearNo = cal.get(Calendar.YEAR) + "-";
        for (int i = elements.size() - 1; i >= 0; i--) {
            try {
                String text = elements.get(i).child(0).text();
                String href =  elements.get(i).attr("href").split("&")[1];
                GrTuanInfo grTuanInfo = new GrTuanInfo();
                grTuanInfo.setUrl(href);
                grTuanInfo.setRemark("http://www.zuanke8.com/forum.php?mod=viewthread&");
                List<GrTuanInfo> list = tuanInfoService.selectGrTuanInfoList(grTuanInfo);
                if (list != null && list.size() > 0) {
                    continue;
                }
                String t = elements.get(i).child(1).text();
                String time = "";
                if (t.contains(yearNo) && t.contains(":")) {
                    String[] strings = t.split(yearNo)[1].split(":");
                    String strings0 = "";
                    if (strings[0].contains("-")) {
                        String[] split = strings[0].split("-");
                        if (split[0].length() == 1) {
                            strings0 += "0" + split[0];
                        } else strings0 += split[0];
                        if (split[1].length() == 4) {
                            strings0 += "-0" + split[1];
                        } else strings0 += "-" + split[1];
                    }
                    if (strings.length > 1)
                        time = yearNo + strings0 + ":" + strings[1].substring(0, 2);
                    else {
                        logger.info("角标越界：" + JsonMapper.toJsonString(strings));
                        time = yearNo + strings0;
                    }
                }
                if(StringUtils.isBlank(time)){
                    continue;
                }
                grTuanInfo.setContent(text);
                grTuanInfo.setTitle(time);
                tuanInfoService.insertGrTuanInfo(grTuanInfo);
                count++;
                /*邮件通知*/
                sendEmail(time + text, grTuanInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return count;
    }

    private void pack0818(Element postList, int count) throws Exception {
        Elements postItems = postList.getElementsByClass("list-group-item");
        for (Element postItem : postItems) {
            String title = DateUtils.getTime() + " " + postItem.text();
            String href = postItem.attr("href");
            GrTuanInfo tuanInfo = new GrTuanInfo();
            tuanInfo.setUrl(Constant.XB0818_HEAD + href);
            List<GrTuanInfo> list = tuanInfoService.selectGrTuanInfoList(tuanInfo);
            if (list != null && list.size() > 0) {
                continue;
            }
            String contents = HttpUtils.sendGetMuliParam(Constant.XB0818_HEAD + href, "",
                    "gbk", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
            Document document1 = Jsoup.parse(contents);
            Elements elementsByClass = document1.getElementsByClass("post-content");
            if (elementsByClass != null && elementsByClass.size() > 0) {
                Element element = elementsByClass.get(0);
                String text = element.child(1).outerHtml();
                String all = text.replaceAll("<br />", "")
                        .replaceAll("<br>", "")
                        .replaceAll(" ", "")
                        .replaceAll("\"", "")
                        .replaceAll("\'", "")
                        .replaceAll("</br>", "")
                        .replaceAll("<img", "");
                tuanInfo.setContent(delHTMLTag(all));
            }

            tuanInfo.setTitle("T_" + title);
            count++;
            tuanInfoService.insertGrTuanInfo(tuanInfo);
            sendEmail(title, tuanInfo);

        }
    }

    private void sendEmail(String title, GrTuanInfo tuanInfo) {
        /*邮件通知*/
        String shi = Constant.XB_KEYWORDS;
        if (StringUtils.isNotBlank(shi)) {
            if (shi.contains(" ")) {
                String[] ss = shi.split(" ");
                for (String s : ss) {
                    if (title.contains(s)) {
//                        SendMailUtil.sendCommonMail("13305695265@189.cn", title, tuanInfo.getContent());
                        SendMailUtil.sendCommonMail(Constant.mails, title,  tuanInfo.getContent());
                        break;
                    }
                }
            } else {
                if (title.contains(shi)) {
//                    SendMailUtil.sendCommonMail("13305695265@189.cn", title, tuanInfo.getContent());
                    SendMailUtil.sendCommonMail(Constant.mails, title,  tuanInfo.getContent());
                }
            }
        }
    }

    //将html转换为纯文本，此方法最后保留了&nbps空格，使用时注意将空格替换掉
    public static String delHTMLTag(String htmlStr) {
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
        String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); //过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); //过滤style标签
        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); //过滤html标签
        return htmlStr.trim(); //返回文本字符串
    }
}
